<template>
  <basic-dialog
    :width="'70%'"
    :visible.sync="visible"
    :title="'批量维护到货周期'"
    :handle-close="handleCloseDialog"
    :handle-opened="handleOpened"
    :show-footer="false"
  >
    <SkusTable
      :table-height="500"
      :data-source="tableInfo.list"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
    >
      <el-row slot="content_context" type="flex" justify="end">
        <BtnRender :render="renderBtnsBar" />
      </el-row>
    </SkusTable>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@supplier/utils/btnsUtils';
import { createExcelByExport } from '@/utils/bizUtils';
import {
  batchAddArrivalTimeService,
  exportArrivalTimeTempService
} from '@api/supplier/innerManagement/arrivalTimeManagement';

export default {
  components: {
    BasicDialog,
    SkusTable,
    BtnRender
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    logisticsCenterList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      importLoading: false,
      exportLoading: false,
      confirmLoading: false,
      tableInfo: {
        list: [],
        loading: false,
        columns: [
          {
            title: '供应商代码',
            key: 'supplierCode',
            width: '110'
          },
          {
            title: '供应商名称',
            key: 'supplierName',
            width: '110'
          },
          {
            title: '供应商类型',
            key: 'supplierTypeName',
          },
          {
            title: '供应商分类',
            key: 'supplierClassifyName',
          },
          {
            title: '供应商管理区域',
            key: 'managementAreaName',
          },
          {
            title: '物流中心',
            key: 'logisticsCenterId',
            width: '160',
            render: (h, { row }) => {
              return <el-select
                size='mini'
                v-model={row.logisticsCenterId}
                onChange={val => { this.handleChangeLogisticsCenter({ row, val }) }}
              >
                { this.logisticsCenterList.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
              </el-select>
            }
          },
          {
            title: '起始时间',
            key: 'arrivalTimeStart',
            width: '245',
            render: (h, { row }) => {
              return <el-time-picker
                size='mini'
                onChange={val => { this.handleTimeChange({ val, row, key: 'arrivalTimeStart' }) }}
                v-model={row.arrivalTimeStart}
                value-format="HH:mm:ss"
                pickerOptions=""
                placeholder="选择到货起始时间">
              </el-time-picker>
            }
          },
          {
            title: '截至时间',
            key: 'arrivalTimeEnd',
            width: '245',
            render: (h, { row }) => {
              return <el-time-picker
                size='mini'
                onChange={val => { this.handleTimeChange({ val, row, key: 'arrivalTimeEnd' }) }}
                v-model={row.arrivalTimeEnd}
                value-format="HH:mm:ss"
                placeholder="选择到货截至时间">
              </el-time-picker>
            }
          },
        ],
      }
    };
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        {
          label: '模板导出',
          method: this.exportTemplateFile,
          loading: this.exportLoading,
          size: 'mini',
        },
        {
          label: '模板导入',
          action: 'srm-export/import/arrival-time',
          type: 'import',
          size: 'mini',
          loadingFn: state => { this.importLoading = state },
          methods: { handleUploadSuccess: this.handleUploadSuccess },
        },
        {
          label: '提交',
          size: 'mini',
          method: this.submitAction,
          loading: this.confirmLoading,
          disabled: this.tableInfo.list.length == 0,
        },
        {
          label: '取消',
          size: 'mini',
          method: this.handleCloseDialog,
        },
      ];
      return getBtnsBar(h, btnsBar);
    },
    // 导出
    async exportTemplateFile () {
      const res = await exportArrivalTimeTempService({}, state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ excelTitle: '到货时间模板', res })
      }
    },
    async submitAction () {
      const res = await batchAddArrivalTimeService(
        this.tableInfo.list,
        state => { this.confirmLoading = state }
      );
      if (res) {
        this.$message.success('操作成功');
        this.$emit('getTableData');
        this.handleCloseDialog();
      }
    },
    handleOpened () {
      this.tableInfo.list = [];
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false);
    },
    // 物流中心切换
    handleChangeLogisticsCenter (data) {
      const { row, val } = data;
      row.logisticsCenter = this.logisticsCenterList.find(item => item.value == val).label;
    },
    // 模板导入成功
    handleUploadSuccess (res) {
      if (res.status !== '0') {
        this.$message.error(res.message || '导入失败');
        return false;
      }
      this.tableInfo.list = res.result || [];
    },
    // 对比时间 时分秒
    compareTime (startTime, endTime) {
      const date = new Date()
      const [startHour, startMinute, startSecond] = startTime.split(':')
      const [endHour, endMinute, endSecond] = endTime.split(':')
      const start = date.setHours(startHour, startMinute, startSecond)
      const end = date.setHours(endHour, endMinute, endSecond)
      return start > end
    },
    // 时间选择
    handleTimeChange (data) {
      const { row, val, key } = data;
      if (key == 'arrivalTimeStart' && row.arrivalTimeEnd) {
        if (this.compareTime(val, row.arrivalTimeEnd)) {
          row.arrivalTimeStart = '';
          return this.$message.warning('起始时间不能大于截至时间')
        }
      }
      if (key == 'arrivalTimeEnd' && row.arrivalTimeStart) {
        if (this.compareTime(row.arrivalTimeStart, val)) {
          row.arrivalTimeEnd = '';
          return this.$message.warning('截至时间不能小于起始时间')
        }
      }
    }
  }
};
</script>
